package com.mti.zhpt.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mti.zhpt.constant.TargetMap;
import com.mti.zhpt.dao.CommandMapper;
import com.mti.zhpt.utils.KeyWorker;
import com.mti.zhpt.dao.EventDetailsMapper;
import com.mti.zhpt.dto.CommandEntity;
import com.mti.zhpt.model.CpPerson;
import com.mti.zhpt.model.EventTimerEntity;
import com.mti.zhpt.model.android.CommandSubmitEntity;
import com.mti.zhpt.shared.Exception.BusinessException;
import com.mti.zhpt.shared.utils.StringUtil;
import com.mti.zhpt.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 命令
 * @Author: zhaopf@mti-sh.cn
 * @Date: 2019/4/28 13:34
 */
@Service("commandServiceImpl")
@Slf4j
public class CommandServiceImpl {

    //注入 RestTemplateBuilder
    @Autowired
    private void initRestTemplate(RestTemplateBuilder builder) {
        this.restTemplate = builder.build();
    }

    @Resource
    private CommandMapper commandMapper;

    @Resource
    private EventDetailsMapper eventDetailsMapper;


    private RestTemplate restTemplate;

    @Value("${web.url}")
    private String webUrl;

    public PageInfo commandAll(String name, String alert, Integer pageNum, Integer pageSize,
                               boolean isLocation, String startTime, String endTime, String unitPoliceId, CommandEntity entity) {
        PageInfo pageInfo = null;
        try {
            /**
             * 命令状态---未反馈30、已反馈40、已作废50  、已签收60、收到70
             */
            List<Integer> statusList = entity.getStatusList();
            pageInfo = null;
            List<EventTimerEntity> entities = null;
            switch (alert) {
                case Constant.DCL_JQ:
                    if (CollectionUtils.isEmpty(statusList)){
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YXD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YDD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YJS));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YCD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YDC));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YFK));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YZF));
                    }
                    Timestamp startTimeDCL = StringUtil.isNotEmpty(startTime) ? Timestamp.valueOf(startTime) : null;
                    Timestamp endTimeDCL = StringUtil.isNotEmpty(endTime) ? Timestamp.valueOf(endTime) : null;
                    PageHelper.startPage(pageNum, pageSize);
                    entities = commandMapper.commandAll(name, statusList, startTimeDCL, endTimeDCL,unitPoliceId,null,entity.getCaseTypeList());
                    /**
                     * 是否显示经纬度
                     */
//                    CommandServiceHelper.isLocation(isLocation, entities, eventDetailsMapper);


                    pageInfo = new PageInfo(entities);

                    break;
                case Constant.LS_JQ:
                    if (CollectionUtils.isEmpty(statusList)){
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YXD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YDD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YJS));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YCD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YDC));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YFK));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YZF));
                    }
                    Timestamp alarmStartTime = StringUtil.isNotEmpty(startTime) ? Timestamp.valueOf(startTime) : null;
                    Timestamp alarmEndTime = StringUtil.isNotEmpty(endTime) ? Timestamp.valueOf(endTime) : null;
                    PageHelper.startPage(pageNum, pageSize);
                    entities = commandMapper.commandAll(name, statusList, alarmStartTime, alarmEndTime,null,entity.getUnitId(),entity.getCaseTypeList());
                    /**
                     * 是否显示经纬度
                     */
//                    CommandServiceHelper.isLocation(isLocation, entities, eventDetailsMapper);
                    pageInfo = new PageInfo(entities);

                    break;
                case Constant.ALL:
                    if (CollectionUtils.isEmpty(statusList)){
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YXD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YDD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YJS));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YCD));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YDC));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YFK));
                        statusList.add((Integer) TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YZF));
                    }

                    PageHelper.startPage(pageNum, pageSize);
                    entities = commandMapper.commandAll(name, statusList, null, null,null,null,entity.getCaseTypeList());
                    /**
                     * 是否显示经纬度
                     */
//                    CommandServiceHelper.isLocation(isLocation, entities, eventDetailsMapper);
                    pageInfo = new PageInfo(entities);

                    break;
                default:
                    throw new BusinessException("alert参数错误");
            }
        } catch (Exception e) {
          log.error("我的警单，历史警单错误：",e);
        }

        return pageInfo;
    }


    public Map<Object, Object> commandTimerId(String  id, Integer distance) {
        Map<Object, Object> result = null;
        try {
            result = new HashMap<>();

            List<Map<String, Object>> resultMoniters = null;
            List<Map<String, Object>> resultJurisdictions = null;

            /**
             * 命令详情
             */
            EventTimerEntity eventTimerEntity = commandMapper.command(id);
            result.put("eventTimerEntity", eventTimerEntity);
            if (eventTimerEntity == null) {
                throw new BusinessException("没有查询到此命令");
            }
            /**
             * 事件详情
             */
            String eventId = eventTimerEntity.getEventId();
            Map<String, Object> eventDetails = eventDetailsMapper.queryDetails(eventId);
            result.put("eventDetails", eventDetails);

            /**
             * 查询事件经纬度
             * 基于（cp_org）
             * 范围内的点
             */
            resultJurisdictions = eventDetailsMapper.queryNearByJurisdictions(eventId, distance);
            for (Map<String, Object> res : resultJurisdictions) {
                Double[] coordinates = {(Double) res.get("longitude"), (Double) res.get("latitude")};
                res.put("coordinates", coordinates);
            }
            /**
             * 查询事件经纬度
             * 基于（cp_moniter）
             * 范围内的点
             */
            resultMoniters = eventDetailsMapper.queryNearByMoniters(eventId, distance);
            for (Map<String, Object> res : resultMoniters) {
                Double[] coordinates = {(Double) res.get("longitude"), (Double) res.get("latitude")};
                res.put("coordinates", coordinates);
            }
            result.put("Jurisdictions", resultJurisdictions);
            result.put("Moniters", resultMoniters);
        } catch (Exception e) {
          log.error("app 查询命令详情错误",e);
        }

        return result;
    }

    @Transactional
    public Integer updateStatus(Integer timerId, Integer status) {
        Integer result = commandMapper.updateStatus(timerId, status);
        String eventid = commandMapper.queryEventid(timerId);
        try {
                Map<Object, Object> map = new HashMap<>();
                map.put("eventid", eventid);
                /**
                 * 提交的内容转发给web
                 */
//                HttpHeaders headers = new HttpHeaders();
//                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//                String body = JSON.toJSONString(map);
//                HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
//                ResponseEntity<String> response = restTemplate.
//                        postForEntity(webUrl + "/app/command-status", requestEntity, String.class);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return result;
    }


    @Transactional
    public void disposeSubmit(CommandSubmitEntity entity) {
        try {

            if (StringUtils.isEmpty(entity.getEventId())){
                throw new BusinessException("eventId不能为空");
            }
            /**
             * 插入指令
             */
            entity.setStatus(60);
            entity.setCreateTime(new Date());
            commandMapper.insertEventTimer(entity);
            entity.setResponseId(KeyWorker.nextId());
            commandMapper.insertEventResponse(entity);
            /**
             * 插入反馈表
             */
            if (entity.getStatus()==60){
                commandMapper.changePoliceStatus(entity.getPoliceCode());
            }
            if (!CollectionUtils.isEmpty(entity.getImagesUrl())) {
                commandMapper.InsertImagesUrl(entity);
            }
            if (!CollectionUtils.isEmpty(entity.getVideosUrl())) {
                commandMapper.InsertVideosUrl(entity);
            }
            if (!CollectionUtils.isEmpty(entity.getAudiosUrl())) {
                commandMapper.InsertAudiosUrl(entity);
            }
            if (!CollectionUtils.isEmpty(entity.getRelevantPerson())) {
                for (CpPerson s : entity.getRelevantPerson()) {
//                    String idNumber =  commandMapper.selectCpPerson(s.getIdNumber());
//                    if (StringUtils.isEmpty(idNumber)){
//                        commandMapper.InsertRelevantUeople(s);
//                    }
                    String id  = commandMapper.selectPersonnel(entity.getEventId(), s.getId());
                    if (id == null) {
                        // 插入相关人信息
                        commandMapper.InsertPersonnel(entity.getEventId(), s.getId(), s.getPersonType());
                    }
                }
            }
            /**
             * 更改事件状态
             * 更改命令状态
             */
            commandMapper.changeEventStatus(entity.getEventId());
            commandMapper.changeTasksStatus(entity);
//            Map<String, Object> map = new HashMap<>();
//            map.put("name", entity.getDeptName());
//            map.put("content", entity.getRemark());
//            map.put("messageType", Constant.FANKUI);
//            map.put("createTime", DateUtil.formatDate(new Date(),"datetime"));
//            map.put("eventId", entity.getEventId());
//
//
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//            String body = JSON.toJSONString(map);
//            HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
//            ResponseEntity<String> response = restTemplate.
//                    postForEntity(webUrl + "/app/feedback", requestEntity, String.class);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BusinessException("指令内容提交or转发给web失败：" + e.getMessage());
        }


    }

    @Transactional
    public void doCommand(CommandSubmitEntity entity) {
        try {

            if (StringUtils.isEmpty(entity.getEventId())||StringUtils.isEmpty(entity.getId())){
                throw new BusinessException("eventId/id不能为空");
            }
            /**
             * 更改命令状态
             */
            commandMapper.changeTasksStatus(entity);

            /**
             * 插入指令
             */
//            entity.setCreateTime(new Date());
//            commandMapper.insertEventTimer(entity);
//            entity.setResponseId(KeyWorker.nextId());
//            commandMapper.insertEventResponse(entity);
            if (entity.getStatus()== TargetMap.TARGETMAP.get(TargetMap.ZLD_KEY_YZF)){
                commandMapper.changePoliceStatus(entity.getPoliceCode());
            }
            commandMapper.changeEventStatus(entity.getEventId());

//
//            Map<String, Object> map = new HashMap<>();
//            map.put("name", entity.getDeptName());
//            map.put("content", entity.getRemark());
//            map.put("messageType", Constant.FANKUI);
//            map.put("createTime", DateUtil.formatDate(new Date(),"datetime"));
//            map.put("eventId", entity.getEventId());
//
//
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//            String body = JSON.toJSONString(map);
//            HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
//            ResponseEntity<String> response = restTemplate.postForEntity(webUrl + "/app/feedback", requestEntity, String.class);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BusinessException("指令内容提交or转发给web失败：" + e.getMessage());
        }


    }

}
